package algorithm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author fangkun
 * @create 2022-05-18-9:37
 *
 * 56
 *合并区间
 */
public class MergeIntervals {

    public static void main(String[] args) {
        int[][] merge = merge(new int[][]{{1, 3}, {2, 6}, {8, 10}});

        for (int[] ints:merge){
            for (int anInt:ints){
                System.out.print(anInt+"\t");
            }
            System.out.println();
        }
    }

    public static int[][] merge(int[][] intervals) {

        if (intervals.length == 0) {
            return new int[0][];
        }

        Arrays.sort(intervals, (a,b) -> {
            return a[0] - b[0];
        });

        List<int[]> merged = new ArrayList<int[]>();

        for (int i = 0; i < intervals.length; ++i) {

            int L = intervals[i][0], R = intervals[i][1];

            if (merged.size() == 0 || merged.get(merged.size() - 1)[1] < L) {

                merged.add(new int[]{L, R});

            } else {

                merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], R);

            }
        }

        return merged.toArray(new int[merged.size()][]);

    }
}
